<template>
  <div>
    <Layout>
      <template #search>
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          :v-show="true"
          label-width="68px"
        >
          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入用户昵称"
              style="width: 200px; height: 32px"
              clearable
              @change="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              type="date"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
              placeholder="Pick a day"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <InputSelect
              text="请输入用户状态"
              :modelValue="queryParams.status"
              :options="statusList"
              @update:modelValue="statusSearch"
            />
          </el-form-item>
          <el-form-item label="删除标识" prop="delFlag">
            <InputSelect
              text="请输入删除标识"
              :modelValue="queryParams.delFlag"
              :options="delFlagList"
              @update:modelValue="delFlagSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="Search"
              @click="handleQuery"
              class="btn-animate btn-animate-1"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              :disabled="multiple"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
        </el-row>
      </template>
      <template #content>
        <el-table :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="编号" align="center" prop="userId" />
          <el-table-column
            label="名字"
            align="center"
            prop="nickName"
            width="100"
          >
          </el-table-column>
          <el-table-column
            label="小程序头像"
            align="center"
            prop="mpAvatar"
            width="100"
          >
            <template #default="scope">
              <ImagePreview
                :src="scope.row.mpAvatar"
                :width="80"
                :height="80"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="后台头像"
            align="center"
            prop="avatar"
            width="100"
          >
            <template #default="scope">
              <ImagePreview :src="scope.row.avatar" :width="80" :height="80" />
            </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column
            label="上次登陆时间"
            align="center"
            prop="lastLoginTime"
          />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                inline-prompt
                :active-value="0"
                active-text="启用"
                :inactive-value="1"
                inactive-text="禁用"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="删除标识" align="center" prop="delFlag">
            <template #default="scope">
              <el-tag v-show="scope.row.delFlag == 0" effect="dark" round>
                正常使用</el-tag
              >
              <el-tag v-show="scope.row.delFlag == 1" effect="dark" round>
                已删除</el-tag
              >
            </template></el-table-column
          >
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <!-- <el-button
                link
                type="primary"
                icon="Postcard"
                @click="handleQrcode(scope.row)"
                >生成二维码</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
        <!-- 添加或修改对话框 -->
        <Dialog
          :show="dialogConfig.show"
          :title="dialogConfig.title"
          :buttons="dialogConfig.buttons"
          width="600px"
          :showCancel="false"
          @close="clear"
          :showClose="false"
          :closeOnClickModal="true"
        >
          <el-form
            ref="userDialogFormRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            label-position="left"
            inline
          >
            <el-form-item label="名字" prop="nickName">
              <el-input
                v-model="form.nickName"
                placeholder="请输入名字"
                style="width: 200px; height: 32px"
                clearable
              />
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入用户邮箱"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="openId" prop="wxOpenId">
              <el-input
                v-model="form.wxOpenId"
                placeholder="请输入微信openId"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>

            <el-form-item label="小程序头像" prop="mpAvatar">
              <ImageUpload
                :imageUrl="form.mpAvatar"
                ref="uploadRef"
                @filePath="getMpAvatarPath"
              />
            </el-form-item>
            <el-form-item label="后台头像" prop="avatar">
              <ImageUpload
                :imageUrl="form.avatar"
                ref="avatarUploadRef"
                @filePath="getAvatarPath"
              />
            </el-form-item>

            <el-form-item label="上次登录时间" prop="lastLoginTime	">
              <el-input
                v-model="form.lastLoginTime"
                placeholder="请输入上次登录时间"
                style="width: 200px; height: 32px"
                clearable
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="注册时间" prop="createTime">
              <el-date-picker
                type="datetime"
                placeholder="注册时间"
                v-model="form.createTime"
                disabled
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <template #default>
                <el-switch
                  v-model="form.status"
                  inline-prompt
                  :active-value="0"
                  active-text="启用"
                  :inactive-value="1"
                  inactive-text="禁用"
                />
              </template>
            </el-form-item>
            <el-form-item label="删除标识" prop="delFlag	">
              <template #default>
                <el-switch
                  v-model="form.delFlag"
                  inline-prompt
                  :active-value="0"
                  active-text="正常使用"
                  :inactive-value="1"
                  inactive-text="已删除"
                />
              </template>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </Dialog>

        <!-- <el-dialog
          :model-value="qrcodeDialogConfig.show"
          :title="qrcodeDialogConfig.title"
          width="400px"
          :showCancel="false"
          @close="closeQrcodeDialog"
          :showClose="false"
          :closeOnClickModal="true"
          style="display: flex; flex-direction: column"
        >
          <vue-qrcode
            :value="qrcodeDialogConfig.qrcode"
            :width="300"
            :color="{ dark: '#000000', light: '#ffffff' }"
            type="image/png"
            style="margin-left: 40px"
          ></vue-qrcode>
          <template #footer>
            <div class="dialog-footer">
              <el-button
                type="primary"
                @click="handleSimulateQrcode"
                icon="ArrowRight"
                >模拟扫码
              </el-button>
            </div>
          </template>
        </el-dialog> -->
      </template>
    </Layout>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  computed,
  onMounted,
  watch,
  toRefs,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Layout from "@/components/Layout/Layout-common.vue";
import {
  getUserInfoList,
  getUserInfo,
  addUserInfo,
  updateUserInfo,
  deleteUserInfo,
  deleteUserInfoBatch,
  scanCode,
} from "@/api/userinfo";
import { download } from "@/utils/request.js";
import { deleteOssFile } from "@/api/page/home.js";
import Dialog from "@/components/Dialog.vue";

// 分页数据
const total = ref(0);
// 用户数据
const userList = ref([]);
// 用户选择项
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 定义 queryFormRef
const queryFormRef = ref(null);
// 搜索查询数据
const queryData = reactive({
  // 搜索栏的数据
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
});
// 搜索-禁止超过当前时间
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};
const { queryParams } = toRefs(queryData);

// 弹窗的表单数据
const formData = reactive({
  // 修改、新增弹窗表单数据
  form: {},
  rules: {
    nickName: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
    ],
    email: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur"],
      },
    ],
    status: [{ required: true, message: "请选择用户状态", trigger: "blur" }],
    delFlag: [{ required: true, message: "请选择删除标识", trigger: "blur" }],
  },
  // 需要删除的文件数组（删除之前存储的文件）
  imgData: [],
});
// 修改、新增弹窗表单数据
const userDialogFormRef = ref();
// 小程序头像上传组件的ref
const uploadRef = ref();
// 后台头像上传组件的ref
const avatarUploadRef = ref();
// 结构属性，转为ref
const { form, rules, imgData } = toRefs(formData);

// 弹窗相关参数
const dialogConfig = reactive({
  show: false,
  title: "",
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

// 二维码弹窗相关参数
const qrcodeDialogConfig = reactive({
  show: false,
  title: "",
  qrcode: "",
});

// 删除标志
const delFlagList = ref([
  { name: "正常", value: "0" },
  { name: "删除", value: "1" },
]);
// 状态
const statusList = ref([
  { name: "启用", value: "0" },
  { name: "禁用", value: "1" },
]);

// 搜索-时间-快捷选择
const shortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];

onMounted(() => {
  getList();
});

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
  };
  getList();
};
// 搜索栏的查询
const handleQuery = () => {
  getList();
};
// 搜索-用户状态的下拉菜单
const statusSearch = (val) => {
  queryParams.value.status = val;
};
// 搜索-删除标识的下拉菜单
const delFlagSearch = (val) => {
  queryParams.value.delFlag = val;
};

// 批量操作
const handleSelectionChange = (val) => {
  ids.value = val.map((item) => item.userId);
  single.value = val.length != 1;
  multiple.value = !val.length;
  console.log("ids:", ids.value);
};

// 导出数据
const handleExport = () => {
  // 发送请求
  download(
    "/userInfo/export",
    ids.value,
    `用户信息_${new Date().getTime()}.xlsx`
  );
};
// 获取所有用户数据
function getList() {
  console.log("queryParams:", queryParams.value);
  getUserInfoList(queryParams.value).then((response) => {
    userList.value = response.rows;
    total.value = response.total;
  });
}

// 弹窗表单重置
function reset() {
  form.value = {
    nickName: null,
    email: null,
    mpAvatar: null,
    createTime: null,
    lastLoginTime: null,
    status: null,
    useSpace: null,
    totalSpace: null,
    delFlag: null,
    avatar: null,
    wxOpenId: null,
  };
  // 清除表单的验证状态
  // dialogFormRef.value.resetFields();
}

/** 新增按钮操作 */
function handleAdd() {
  dialogConfig.show = true;
  dialogConfig.title = "添加用户信息";
  reset();
}

// 修改按钮操作
function handleUpdate(row) {
  const userId = row.userId || ids.value;
  getUserInfo(userId).then((response) => {
    form.value = response.data;
    //
    dialogConfig.show = true;
    dialogConfig.title = "修改用户信息";
  });
}

// 生成二维码
const handleQrcode = (row) => {
  // 打开二维码弹窗
  qrcodeDialogConfig.show = true;
  qrcodeDialogConfig.title = "二维码";
  // 生成二维码
  qrcodeDialogConfig.qrcode =
    "https://mp.diandianjfb.com/web/index.getwechatuserinfo";
  // "http://localhost:8081/api/XcxUser/" + row.userId;
  console.log("row:", row);
};

// 模拟扫码
const handleSimulateQrcode = (row) => {
  scanCode().then((response) => {});
};

// 关闭二维码弹窗
const closeQrcodeDialog = () => {
  qrcodeDialogConfig.show = false;
};

//  删除按钮操作
const handleDelete = (row) => {
  // 判断参数ids是否有值
  // 有,则执行删除多个操作
  if (ids.value.length > 0) {
    ElMessageBox.confirm("是否确认删除", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function () {
      deleteUserInfoBatch(ids.value)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("删除成功");
          }
          if (result.code == 500) {
            ElMessage.error("删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("删除失败");
        });
      // 重新获取数据
      setTimeout(() => {
        getList();
      }, 200);
    });
  }
  if (ids.value.length == 0) {
    ElMessageBox.confirm("是否确认删除", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function () {
      console.log("row:", row);
      // 删除操作
      deleteUserInfo(row.userId)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("删除成功");
          }
          if (result.code == 500) {
            ElMessage.error("删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("删除失败");
        });
      // 重新获取数据
      setTimeout(() => {
        getList();
      }, 200);
    });
  }
};

// 弹框确认  修改/添加
const submitForm = () => {
  userDialogFormRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("参数验证错误，请仔细填写表单数据!");
      return;
    }
    // 修改操作
    if (dialogConfig.title == "修改用户信息") {
      // console.log("修改操作", form.value);
      // 上传新的图片，获取数据
      updateUserInfo(form.value)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("修改成功");
          }
        })
        .catch((err) => {
          ElMessage.error("修改失败");
        });
    }
    // 添加操作
    else if (dialogConfig.title == "添加用户信息") {
      // 校验表单参数，是否填写
      addUserInfo(form.value)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("添加成功");
          } else {
            ElMessage.error("添加失败");
          }
        })
        .catch((err) => {});
    }
    // 判断ImgData是否有值，有则
    if (imgData.value.length) {
      console.log("删除方法执行了吗！");
      // 向后端发起请求，删除旧文件
      deleteOssFile(imgData.value);
    }
    // 重新获取数据
    setTimeout(() => {
      getList();
    }, 100);
    dialogConfig.show = false;
  });
};

// 数据还原
const clear = () => {
  // 清除上传子组件的文件列表和img
  uploadRef.value.clearFileList();
  avatarUploadRef.value.clearFileList();
  imgData.value = [];
  setTimeout(() => {
    reset();
  }, 100);
  dialogConfig.show = false;
};
// 获取小程序头像的路径
const getMpAvatarPath = (filePath) => {
  // 上传文件之前，把前一个文件路径，记录下来
  // 获取文件名 保存之前的文件的路径，便于删除
  let fileName = form.value.url?.split("/").pop() || "";
  imgData.value.push(fileName);
  //   修改form的属性值
  form.value.mpAvatar = filePath;
  console.log("mpAvatar:", filePath);
};

// 获取后台头像的路径
const getAvatarPath = (filePath) => {
  // 上传文件之前，把前一个文件路径，记录下来
  // 获取文件名 保存之前的文件的路径，便于删除
  let fileName = form.value.url?.split("/").pop() || "";
  imgData.value.push(fileName);
  //   修改form的属性值
  form.value.avatar = filePath;
  console.log("avatar:", filePath);
};
</script>

<style lang="scss" scoped>
.btn-animate {
  position: relative;
  width: 79px;
  height: 32px;
  line-height: 40px;
  border: none;
  border-radius: 5px;
  background: #027efb;
  color: #fff;
  text-align: center;
}

.btn-animate-1 {
  &::before,
  &::after {
    content: "";
    position: absolute;
    height: 2px;
    width: 0;
    background: #027efb;
    transition: all 0.6s ease;
  }

  &::before {
    top: 0;
    right: 0;
  }

  &::after {
    left: 0;
    bottom: 0;
  }

  &:hover {
    color: #027efb;
    background: transparent;

    &::before,
    &::after {
      width: 100%;
    }
  }
}
</style>
